package sunn.android.Conn;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;


import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.util.Log;

public class AndroidServer implements Runnable
{
	public static final String 			DEBUG_TAG 			=	"SERVER";
	public static final int 			SERVER_PORT 		=	60000;
	
	String 								server_ip_address 	= 	null;  
	ServerSocket 						server_socket 		= 	null;
	LocalServerSocket 					lss 				= 	null;
	
	boolean 							alive 				=	false;
	
	public final ServerSocket getIpAddress() 
	{
		return server_socket;
	}
	
	public void run()
	{
		try
		{
//			server_socket = new ServerSocket(SERVER_PORT);
			
			server_ip_address = AndroidNetwork.getLocalIpAddress();
			
			lss = new LocalServerSocket( server_ip_address );
			
			alive = true;
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		while( alive )
		{
			if( alive == false)
				break;
			
//			Socket socket = null;
			
			LocalSocket socket = null;
			
			
			try
			{
				Log.i(DEBUG_TAG, "READY to date from client , ip :" + server_ip_address + "port : "+ SERVER_PORT);
				
				socket = lss.accept();
			
//				socket = server_socket.accept();
				
				InputStreamReader isr = new InputStreamReader( socket.getInputStream() );
				
				BufferedReader br = new BufferedReader( isr );
				
				String str = br.readLine();
				
				Log.d(DEBUG_TAG, "received: " + str + server_ip_address);
			}
			catch (IOException e)
			{
				e.printStackTrace();
				Log.e(DEBUG_TAG, e.getMessage());
			}
			finally
			{
				try
				{
					if( socket != null )
					{
						socket.close();
						Log.i(DEBUG_TAG, "Close Jam Server");
					}
				}
				catch (IOException e)
				{
					e.printStackTrace();
					Log.e(DEBUG_TAG, e.getMessage());
				}
			}
		}
		
		try 
		{
			if( lss != null)
			{
				lss.close();	
			}
			
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}
}